package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"user-reg-mod/cache"
	"user-reg-mod/models"
)

func ArticleAdd(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	data := models.Article{
		Title:   title,
		Comment: comment,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func ArticleList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var article models.Article
	redis_key := "article_page_size" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Order("id dsc").Debug().Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Table("articles").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  article,
		"total": total,
	})
	return
}
func ArticleDetail(c *gin.Context) {
	aid := c.Query("aid")
	var article models.Article
	redis_key := "article_detail_" + aid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", aid).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return
}
